package com.laze.mywanandroid.ui.main.fragment.home

import androidx.lifecycle.MutableLiveData
import com.chad.library.adapter.base.loadmore.LoadMoreStatus
import com.laze.mywanandroid.bean.Banner
import com.laze.mywanandroid.base.BaseViewModel
import com.laze.mywanandroid.bean.ArticleData


class HomeViewModel : BaseViewModel() {

    companion object {
        const val INIT_PAGE = 0
    }

    private val repository by lazy { HomeRepository() }

    val banner = MutableLiveData<List<Banner>>()
    val articleList: MutableLiveData<MutableList<ArticleData>> = MutableLiveData()
    val loadMoreStatus = MutableLiveData<LoadMoreStatus>()
    var page = 0

    fun getData() {
        launch(
            block = {
                banner.value = repository.getBanner()

                val topList = async {
                    repository.getTopArticle()
                }.await().apply {
                    forEach {
                        it.isTop = true
                    }
                }

                val mainList = async {
                    repository.getArticle(page)
                }.await().apply {
                    page = curPage
                }

                articleList.value = mutableListOf<ArticleData>().apply {
                    addAll(topList)
                    addAll(mainList.datas)
                }

            },
            error = {
                page = INIT_PAGE
            }
        )
    }

    fun loadMore() {
        loadMoreStatus.value = LoadMoreStatus.Loading
        launch(
            block = {
                val newList = repository.getArticle(page)
                page = newList.curPage
                val currentList = articleList.value ?: mutableListOf()
                currentList.addAll(newList.datas)
                articleList.value = currentList
                loadMoreStatus.value = if (newList.offset >= newList.total) {
                    LoadMoreStatus.End
                } else {
                    LoadMoreStatus.Complete
                }
            },
            error = {
                page = INIT_PAGE
                loadMoreStatus.value = LoadMoreStatus.Fail
            }
        )
    }
}
